package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.validation.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.Arith;
import com.ruoyi.common.utils.Condition;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.ip.Address;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.domain.SysUserPost;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;

/**
 * 用户 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    
	private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    protected Validator validator;
    
    @Autowired
	private RedisCache redisCache;
    
    public final static String KEY_USER = "key:user:";
    
    public final static String KEY_USER_TOTAL = "key:user:total";

    /**
     * 根据条件分页查询用户列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user)
    {
        return userMapper.selectUserList(user);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user)
    {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user)
    {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     * 
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName)
    {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     * 
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId)
    {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     * 
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName)
    {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list))
        {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     * 
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName)
    {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list))
        {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     * 
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName)
    {
        int count = userMapper.checkUserNameUnique(userName);
        if (count > 0)
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     * 
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user)
    {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin())
        {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     * 
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()))
        {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users))
            {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user)
    {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 注册用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user)
    {
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user)
    {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return userMapper.updateUser(user);
    }

    /**
     * 用户授权角色
     * 
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds)
    {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user){
        return userMapper.updateById(user);
    }

    /**
     * 修改用户头像
     * 
     * @param userName 用户名
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(Long userId, String avatar)
    {
        return userMapper.updateUserAvatar(userId, avatar) > 0;
    }

    /**
     * 重置用户密码
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     * 
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password)
    {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     * 
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user)
    {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     * 
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user)
    {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts))
        {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
            for (Long postId : posts)
            {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     * 
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds)
    {
        if (StringUtils.isNotEmpty(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     * 
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId)
    {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     * 
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds)
    {
        for (Long userId : userIds)
        {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     * 
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, user);
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

	@Override
	public SysUser selectUserByPhone(String phone) {
		return baseMapper.selectUserByPhone(phone);
	}

	@Override
	public SysUser selectUserByOpenId(String openId) {
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		SysUser entity = new SysUser();
		entity.setOpenId(openId);
		queryWrapper.setEntity(entity);
		return baseMapper.selectOne(queryWrapper);
	}

	@Override
	public SysUser getUserInfo(Long userId) {
		return baseMapper.selectUserById(userId);
	}

	@Override
	public void updateLoginUser(SysUser sysUser) {
		userMapper.updateById(sysUser);
	}

	@Override
	public SysUser saveUserByWx(SysUser user) {
		SysUser sysUser = selectUserByOpenId(user.getOpenId());
		if(sysUser == null){
			// 自动注册
			baseMapper.insert(user);
			return user;
		}else{
			sysUser.setAppId(user.getAppId());
			sysUser.setLat(user.getLat());
			sysUser.setLon(user.getLon());
			sysUser.setProvince(user.getProvince());
			sysUser.setCity(user.getCity());
			sysUser.setDistrict(user.getDistrict());
			sysUser.setToken(user.getToken());
			baseMapper.updateById(sysUser);
			return sysUser;
		}
	}

	@Override
	public void saveUserByPhone(String phone) {
		SysUser sysUser = baseMapper.selectUserByPhone(phone);
		String token = IdUtils.fastUUID();
		Address address = AddressUtils.getAddressByIP();
		String friendId = RandomUtil.randomNumbers(11);
		if(sysUser == null){
			// 自动注册
			sysUser = new SysUser();
			sysUser.setFriendId(Long.valueOf(friendId));
			sysUser.setDeptId(100L);
			sysUser.setPhonenumber(phone);
			sysUser.setNickName(friendId);
			sysUser.setUserType(UserType.APP.getCode());
			sysUser.setLat(address.getLat());
			sysUser.setLon(address.getLng());
			sysUser.setProvince(address.getProvince());
			sysUser.setCity(address.getCity());
			sysUser.setDistrict(address.getDistrict());
			sysUser.setToken(token);
			baseMapper.insert(sysUser);
		}else{
			sysUser.setToken(token);
			baseMapper.updateById(sysUser);
		}
	}

	@Override
	public SysUser getInfoById(SysUser user) {
		SysUser su = baseMapper.selectById(SecurityUtils.getUserId());
		user.setLon(su.getLon());
		user.setLat(su.getLat());
		
		SysUser sysUser = userMapper.getInfoById(user);
		
		if("0".equals(sysUser.getWechatStatus()) && StringUtils.isNotBlank(sysUser.getWechat())){
			sysUser.setWechatFlag(true);
		}else{
			sysUser.setWechatFlag(false);
		}
		
		if(StringUtils.isNotBlank(sysUser.getWechat())){
			sysUser.setInvite(true);
			sysUser.setWechatFlag(true);
		}else{
			sysUser.setInvite(false);
		}
		sysUser.setWechat(null);
		sysUser.setInviteCode(null);
		sysUser.setDistance(String.valueOf(Arith.div(sysUser.getMi(), 1000.00, 2)));
		sysUser.setCoinLevel(StringUtils.getCoinLevel(sysUser.getPayNum()));
		return sysUser;
	}

	@Override
	public SysUser getMyInfo(SysUser user) {
		SysUser sysUser = baseMapper.selectById(user.getUserId());
		sysUser.setIsVip(false);
		if(sysUser.getVipEndTime() != null){
			Date now = new Date();
			if(now.compareTo(sysUser.getVipEndTime()) < 0){
				sysUser.setIsVip(true);
			}
			sysUser.setVipEndDate(DateUtil.formatDate(sysUser.getVipEndTime()));
		}
		return sysUser;
	}

	/**
	 * 
	 */
	@Override
	public void updateUserPlan() {
		Integer size = RandomUtil.randomInt(1, 10);
		IPage<SysUser> page = new Page<>(1, size);
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		SysUser entity = new SysUser();
		entity.setUserType(UserType.APP.getCode());
		queryWrapper.setEntity(entity);
		queryWrapper.orderByAsc("update_time");
		List<SysUser> userList = baseMapper.selectPage(page, queryWrapper).getRecords();
		for(SysUser user: userList){
			user.setUpdateTime(DateUtil.date());
			baseMapper.updateById(user);
		}
	}

	@Override
	public TableDataInfo getListByPayNum(SysUser user) {
		user.setUserType(UserType.APP.getCode());
		SysUser sysUser = baseMapper.selectById(SecurityUtils.getUserId());
		user.setLon(sysUser.getLon());
		user.setLat(sysUser.getLat());
		
		if("0".equals(sysUser.getSex())){
			user.setSex("1");
		}else{
			user.setSex("0");
		}
		
		/*if("wx2b5596fc2c4454d4".equals(sysUser.getAppId()) || "wx3226c36e63a23936".equals(sysUser.getAppId())){
			user.setAppId(sysUser.getAppId());
		}
		
		if(sysUser.getVisitUserId() != null){
			user.setAppId(sysUser.getAppId());
		}*/
		
		user.setAppId(sysUser.getAppId());
		
		if("wxb3279108e13e4e57".equals(sysUser.getAppId()) || "wx496d41494fd03cf7".equals(sysUser.getAppId()) || "wx4a8ce56c55215ee0".equals(sysUser.getAppId())){
			user.setAppId(null);
		}
		user.setAppId(null);
		
		IPage<SysUser> page = baseMapper.getListByPayNum(Condition.getPage(user), user);
		
		for(SysUser su : page.getRecords()){
			if("0".equals(su.getWechatStatus()) && StringUtils.isNotBlank(su.getWechat())){
				su.setWechatFlag(true);
			}else{
				su.setWechatFlag(false);
			}
			
			if(StringUtils.isNotBlank(su.getInviteCode()) && "1".equals(su.getWechatCheck())){
				su.setInvite(true);
				su.setWechatFlag(true);
			}else{
				su.setInvite(false);
			}
			su.setWechat(null);
			su.setInviteCode(null);
			su.setDistance(String.valueOf(Arith.div(su.getMi(), 1000.00, 2)));
			su.setCoinLevel(StringUtils.getCoinLevel(su.getPayNum()));
		}
		return Condition.getTableDataInfo(page.getRecords(), page.getTotal());
	}

	@Override
	public List<SysUser> selectListByFans(SysUser user) {
		user.setUserType(UserType.APP.getCode());
		if(StringUtils.isBlank(user.getLon())){
			Address address = AddressUtils.getAddressByIP();
			user.setLon(address.getLng());
			user.setLat(address.getLat());
		}
		List<SysUser> userList = userMapper.getListByFans(user);
		for(SysUser su : userList){
			if("0".equals(su.getWechatStatus()) && StringUtils.isNotBlank(su.getWechat())){
				su.setWechatFlag(true);
			}else{
				su.setWechatFlag(false);
			}
			
			if(StringUtils.isNotBlank(su.getInviteCode()) && "1".equals(su.getWechatCheck())){
				su.setInvite(true);
				su.setWechatFlag(true);
			}else{
				su.setInvite(false);
			}
			su.setWechat(null);
			su.setInviteCode(null);
			su.setDistance(String.valueOf(Arith.div(su.getMi(), 1000.00, 2)));
		}
		return userList;
	}

	@Override
	public SysUser getMyNum() {
		SysUser sysUser = baseMapper.selectById(SecurityUtils.getUserId());
		if(sysUser.getVipEndTime() != null){
			Date now = new Date();
			if(now.compareTo(sysUser.getVipEndTime()) < 0){
				// 会员没有过期
				if(sysUser.getNextTime() == null){
					sysUser.setWechatNum(10);
					sysUser.setPublishNum(3);
					Date nextTime = DateUtils.getDayLast();
					sysUser.setNextTime(nextTime);
				}else{
					if(now.compareTo(sysUser.getNextTime()) > 0){
						sysUser.setWechatNum(10);
						sysUser.setPublishNum(3);
						Date nextTime = DateUtils.getDayLast();
						sysUser.setNextTime(nextTime);
					}
				}
			}else{
				// 会员过期
				sysUser.setPublishNum(0);
				sysUser.setWechatNum(0);
			}
		}else{
			sysUser.setPublishNum(0);
			sysUser.setWechatNum(0);
		}
		baseMapper.updateById(sysUser);
		return sysUser;
	}

	@Override
	public TableDataInfo getPageList(SysUser user) {
		user.setUserType(UserType.APP.getCode());
		SysUser sysUser = baseMapper.selectById(SecurityUtils.getUserId());
		user.setLon(sysUser.getLon());
		user.setLat(sysUser.getLat());
		if("0".equals(sysUser.getSex())){
			user.setSex("1");
		}else{
			user.setSex("0");
		}
		
		/*if("wx2b5596fc2c4454d4".equals(sysUser.getAppId()) || "wx3226c36e63a23936".equals(sysUser.getAppId())){
			user.setAppId(sysUser.getAppId());
		}
		
		if(sysUser.getVisitUserId() != null){
			user.setAppId(sysUser.getAppId());
		}*/
		
		user.setAppId(sysUser.getAppId());
		
		if("wxb3279108e13e4e57".equals(sysUser.getAppId()) || "wx496d41494fd03cf7".equals(sysUser.getAppId()) || "wx4a8ce56c55215ee0".equals(sysUser.getAppId())){
			user.setAppId(null);
		}
		user.setAppId(null);
		
		IPage<SysUser> page = baseMapper.selectPageList(Condition.getPage(user), user);
		
		for(SysUser su : page.getRecords()){
			if("0".equals(su.getWechatStatus()) && StringUtils.isNotBlank(su.getWechat())){
				su.setWechatFlag(true);
			}else{
				su.setWechatFlag(false);
			}
			
			if(StringUtils.isNotBlank(su.getInviteCode()) && "1".equals(su.getWechatCheck())){
				su.setInvite(true);
				su.setWechatFlag(true);
			}else{
				su.setInvite(false);
			}
			su.setWechat(null);
			su.setInviteCode(null);
			su.setDistance(String.valueOf(Arith.div(su.getMi(), 1000.00, 2)));
			su.setCoinLevel(StringUtils.getCoinLevel(su.getPayNum()));
		}
		return Condition.getTableDataInfo(page.getRecords(), page.getTotal());
	}

	@Override
	public TableDataInfo getPageListByTop(SysUser user) {
		user.setUserType(UserType.APP.getCode());
		SysUser sysUser = baseMapper.selectById(SecurityUtils.getUserId());
		user.setLon(sysUser.getLon());
		user.setLat(sysUser.getLat());
		
		if("0".equals(sysUser.getSex())){
			user.setSex("1");
		}else{
			user.setSex("0");
		}
		
		/*if("wx2b5596fc2c4454d4".equals(sysUser.getAppId()) || "wx3226c36e63a23936".equals(sysUser.getAppId())){
			user.setAppId(sysUser.getAppId());
		}
		
		if(sysUser.getVisitUserId() != null){
			user.setAppId(sysUser.getAppId());
		}*/
		
		user.setAppId(sysUser.getAppId());
		
		if("wxb3279108e13e4e57".equals(sysUser.getAppId()) || "wx496d41494fd03cf7".equals(sysUser.getAppId()) || "wx4a8ce56c55215ee0".equals(sysUser.getAppId())){
			user.setAppId(null);
		}
		user.setAppId(null);
		
		IPage<SysUser> page = baseMapper.selectPageListByTop(Condition.getPage(user), user);
		
		for(SysUser su : page.getRecords()){
			if("0".equals(su.getWechatStatus()) && StringUtils.isNotBlank(su.getWechat())){
				su.setWechatFlag(true);
			}else{
				su.setWechatFlag(false);
			}
			
			if(StringUtils.isNotBlank(su.getInviteCode()) && "1".equals(su.getWechatCheck())){
				su.setInvite(true);
				su.setWechatFlag(true);
			}else{
				su.setInvite(false);
			}
			su.setWechat(null);
			su.setInviteCode(null);
			su.setDistance(String.valueOf(Arith.div(su.getMi(), 1000.00, 2)));
			su.setCoinLevel(StringUtils.getCoinLevel(su.getPayNum()));
		}
		return Condition.getTableDataInfo(page.getRecords(), page.getTotal());
	}

	@Override
	public TableDataInfo getPageListByCity(SysUser user) {
		if(user.getMi() == 0){
			user.setMi(200000);
		}
		user.setUserType(UserType.APP.getCode());
		SysUser sysUser = baseMapper.selectById(SecurityUtils.getUserId());
		
		Boolean flag = false;
		
		if("wx2b5596fc2c4454d4".equals(sysUser.getAppId())){
			if(sysUser.getPayNum() < 10){
				flag = true;
			}
		}
		
		if(flag){
			user.setIdCardStatus("1");
		}
		
		user.setLon(sysUser.getLon());
		user.setLat(sysUser.getLat());
		user.setAppId(null);
		
		IPage<SysUser> pageBean = Condition.getPage(user);
		if(pageBean.getCurrent() > 1){
			Date now = new Date();
			// 判断是否是会员
			if(sysUser.getVipEndTime() == null){
				throw new ServiceException("同城只对会员开放，请充值",788);
			}else{
				if(now.compareTo(sysUser.getVipEndTime()) > 0){
					throw new ServiceException("同城只对会员开放，请充值",788);
				}
			}
		}
		IPage<SysUser> page = baseMapper.selectPageListByCity(pageBean, user);
		for(SysUser su : page.getRecords()){
			if("0".equals(su.getWechatStatus()) && StringUtils.isNotBlank(su.getWechat())){
				su.setWechatFlag(true);
			}else{
				su.setWechatFlag(false);
			}
			
			if(StringUtils.isNotBlank(su.getInviteCode()) && "1".equals(su.getWechatCheck())){
				su.setInvite(true);
				su.setWechatFlag(true);
			}else{
				su.setInvite(false);
			}
			su.setWechat(null);
			su.setInviteCode(null);
			su.setDistance(String.valueOf(Arith.div(su.getMi(), 1000.00, 2)));
			su.setCoinLevel(StringUtils.getCoinLevel(su.getPayNum()));
		}
		return Condition.getTableDataInfo(page.getRecords(), page.getTotal());
	}

	@Override
	public TableDataInfo getPageListByVip(SysUser user) {
		user.setUserType(UserType.APP.getCode());
		SysUser sysUser = baseMapper.selectById(SecurityUtils.getUserId());
		user.setLon(sysUser.getLon());
		user.setLat(sysUser.getLat());
		
		/*if("wx2b5596fc2c4454d4".equals(sysUser.getAppId()) || "wx3226c36e63a23936".equals(sysUser.getAppId())){
			user.setAppId(sysUser.getAppId());
		}
		
		if(sysUser.getVisitUserId() != null){
			user.setAppId(sysUser.getAppId());
		}*/
		
		user.setAppId(sysUser.getAppId());
		
		if("wxb3279108e13e4e57".equals(sysUser.getAppId()) || "wx496d41494fd03cf7".equals(sysUser.getAppId()) || "wx4a8ce56c55215ee0".equals(sysUser.getAppId())){
			user.setAppId(null);
		}
		user.setAppId(null);
		
		IPage<SysUser> page = baseMapper.selectPageListByVip(Condition.getPage(user), user);
		
		for(SysUser su : page.getRecords()){
			if("0".equals(su.getWechatStatus()) && StringUtils.isNotBlank(su.getWechat())){
				su.setWechatFlag(true);
			}else{
				su.setWechatFlag(false);
			}
			
			if(StringUtils.isNotBlank(su.getInviteCode()) && "1".equals(su.getWechatCheck())){
				su.setInvite(true);
				su.setWechatFlag(true);
			}else{
				su.setInvite(false);
			}
			su.setWechat(null);
			su.setInviteCode(null);
			su.setDistance(String.valueOf(Arith.div(su.getMi(), 1000.00, 2)));
			su.setCoinLevel(StringUtils.getCoinLevel(su.getPayNum()));
		}
		return Condition.getTableDataInfo(page.getRecords(), page.getTotal());
	}

	@Override
	public List<SysUser> getUserByUnionId(String wxId, String unionId) {
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		SysUser entity = new SysUser();
		entity.setWxId(wxId);
		entity.setUnionId(unionId);
		queryWrapper.setEntity(entity);
		queryWrapper.isNull("wx_open_id");
		queryWrapper.orderByDesc("login_date");
		return baseMapper.selectList(queryWrapper);
	}

	@Override
	public SysUser getRandomUser() {
		List<SysUser> list = baseMapper.getRandomUser();
		int rd = RandomUtil.randomInt(list.size());
		return list.get(rd);
	}

	@Override
	public TableDataInfo getListByOpen(SysUser user) {
		if(StringUtils.isBlank(user.getLon())){
			Address address = AddressUtils.getAddressByIP();
			user.setLon(address.getLng());
			user.setLat(address.getLat());
		}
		user.setUserType(UserType.APP.getCode());
		if(user.getUserId() != null && user.getUserId() > 0){
			SysUser sysUser = baseMapper.selectById(user.getUserId());
			if("0".equals(sysUser.getSex())){
				user.setSex("1");
			}else{
				user.setSex("0");
			}
			user.setLon(sysUser.getLon());
			user.setLat(sysUser.getLat());
		}
		
		user.setAppId(null);
		
		IPage<SysUser> page = baseMapper.selectPageListByOpen(Condition.getPage(user), user);
		
		for(SysUser su : page.getRecords()){
			if("0".equals(su.getWechatStatus()) && StringUtils.isNotBlank(su.getWechat())){
				su.setWechatFlag(true);
			}else{
				su.setWechatFlag(false);
			}
			
			if(StringUtils.isNotBlank(su.getInviteCode()) && "1".equals(su.getWechatCheck())){
				su.setInvite(true);
				su.setWechatFlag(true);
			}else{
				su.setInvite(false);
			}
			su.setWechat(null);
			su.setInviteCode(null);
			su.setDistance(String.valueOf(Arith.div(su.getMi(), 1000.00, 2)));
			su.setCoinLevel(StringUtils.getCoinLevel(su.getPayNum()));
		}
		return Condition.getTableDataInfo(page.getRecords(), page.getTotal());
	}

	@Override
	public TableDataInfo getPageListByHot(SysUser user) {
		user.setUserType(UserType.APP.getCode());
		SysUser sysUser = baseMapper.selectById(SecurityUtils.getUserId());
		user.setLon(sysUser.getLon());
		user.setLat(sysUser.getLat());
		user.setUserId(sysUser.getUserId());
		
		if(StringUtils.isBlank(user.getSex())){
			if("0".equals(sysUser.getSex())){
				user.setSex("1");
			}else{
				user.setSex("0");
			}
		}
		
		/*if("wx2b5596fc2c4454d4".equals(sysUser.getAppId()) || "wx3226c36e63a23936".equals(sysUser.getAppId())){
			user.setAppId(sysUser.getAppId());
		}
		
		if(sysUser.getVisitUserId() != null){
			user.setAppId(sysUser.getAppId());
		}*/
		
		user.setAppId(sysUser.getAppId());
		
		if("wxb3279108e13e4e57".equals(sysUser.getAppId()) || "wx496d41494fd03cf7".equals(sysUser.getAppId()) || "wx4a8ce56c55215ee0".equals(sysUser.getAppId())){
			user.setAppId(null);
		}
		user.setAppId(null);
		
		IPage<SysUser> page = baseMapper.selectPageListByHot(Condition.getPage(user), user);
		
		for(SysUser su : page.getRecords()){
			if("0".equals(su.getWechatStatus()) && StringUtils.isNotBlank(su.getWechat())){
				su.setWechatFlag(true);
			}else{
				su.setWechatFlag(false);
			}
			
			if(StringUtils.isNotBlank(su.getInviteCode()) && "1".equals(su.getWechatCheck())){
				su.setInvite(true);
				su.setWechatFlag(true);
			}else{
				su.setInvite(false);
			}
			su.setWechat(null);
			su.setInviteCode(null);
			su.setDistance(String.valueOf(Arith.div(su.getMi(), 1000.00, 2)));
			su.setCoinLevel(StringUtils.getCoinLevel(su.getPayNum()));
		}
		return Condition.getTableDataInfo(page.getRecords(), page.getTotal());
	}

	@Override
	public SysUser getUserInfoById(SysUser user) {
		user.setUserType(UserType.APP.getCode());
		Address address = AddressUtils.getAddressByIP();
		user.setLon(address.getLng());
		user.setLat(address.getLat());
		
		SysUser sysUser = userMapper.getInfoById(user);
		
		if("0".equals(sysUser.getWechatStatus()) && StringUtils.isNotBlank(sysUser.getWechat())){
			sysUser.setWechatFlag(true);
		}else{
			sysUser.setWechatFlag(false);
		}
		
		if(StringUtils.isNotBlank(sysUser.getWechat())){
			sysUser.setInvite(true);
			sysUser.setWechatFlag(true);
		}else{
			sysUser.setInvite(false);
		}
		sysUser.setWechat(null);
		sysUser.setInviteCode(null);
		sysUser.setDistance(String.valueOf(Arith.div(sysUser.getMi(), 1000.00, 2)));
		sysUser.setCoinLevel(StringUtils.getCoinLevel(sysUser.getPayNum()));
		return sysUser;
	}

	@Override
	public TableDataInfo getListByPage(SysUser user) {
		user.setUserType(UserType.APP.getCode());
		IPage<SysUser> page = baseMapper.getListByPage(Condition.getPage(user), user);
		return Condition.getTableDataInfo(page.getRecords(), page.getTotal());
	}

	@Override
	public SysUser getWxOpenIdById(SysUser user) {
		return userMapper.getWxOpenIdById(user);
	}

	@Override
	@Transactional
	public void updateWxOpenId(SysUser sysUser) {
		userMapper.updateWxOpenId(sysUser);
	}

	@Override
	public SysUser getRandomUserByUser(SysUser su) {
		SysUser user = new SysUser();
		if("0".equals(su.getSex())){
			user.setSex("1");
		}else{
			user.setSex("0");
		}
		user.setWxId("gh_b0cfae9edc73");
		user.setUserType("01");
		user.setLon(su.getLon());
		user.setLat(su.getLat());
		List<SysUser> list = baseMapper.getRandomUserByUser(user);
		if(CollectionUtils.isEmpty(list)){
			return null;
		}
		int rd = RandomUtil.randomInt(list.size());
		return list.get(rd);
	}

	@Override
	public List<SysUser> getUserNotNullByUnionId(String wxId, String unionId) {
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		SysUser entity = new SysUser();
		entity.setWxId(wxId);
		entity.setUnionId(unionId);
		queryWrapper.setEntity(entity);
		queryWrapper.isNotNull("wx_open_id");
		queryWrapper.orderByDesc("login_date");
		return baseMapper.selectList(queryWrapper);
	}

	@Override
	public void addBlackByUnionId(String unionId) {
		if(StringUtils.isBlank(unionId)){
			return;
		}
		// 如果有一个被封号，就全部封号
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		SysUser entity = new SysUser();
		entity.setUnionId(unionId);
		entity.setStatus("1");
		queryWrapper.setEntity(entity);
		List<SysUser> userList = baseMapper.selectList(queryWrapper);
		if(!CollectionUtils.isEmpty(userList)){
			QueryWrapper<SysUser> qw = new QueryWrapper<>();
			SysUser en = new SysUser();
			en.setUnionId(unionId);
			en.setStatus("0");
			qw.setEntity(en);
			List<SysUser> ul = baseMapper.selectList(qw);
			for(SysUser u : ul){
				u.setStatus("1");
				baseMapper.updateById(u);
			}
		}
	}

	@Override
	public boolean updateUserIdCardFront(Long userId, String idCardFront) {
		SysUser user = baseMapper.selectById(userId);
		user.setIdCardFront(idCardFront);
		baseMapper.updateById(user);
		return true;
	}

	@Override
	public boolean updateUserIdCardBack(Long userId, String idCardBack) {
		SysUser user = baseMapper.selectById(userId);
		user.setIdCardBack(idCardBack);
		baseMapper.updateById(user);
		return true;
	}

	@Override
	public TableDataInfo getPageUserListByCity(SysUser user) {
		user.setUserType(UserType.JB.getCode());
		SysUser sysUser = null;
		if(user.getUserId() != null && user.getUserId() > 0){
			sysUser = baseMapper.selectById(user.getUserId());
			if(StringUtils.isBlank(user.getLat()) && StringUtils.isBlank(user.getLon())){
				user.setLon(sysUser.getLon());
				user.setLat(sysUser.getLat());
			}
			user.setAppId(sysUser.getAppId());
		}
		
		IPage<SysUser> pageBean = Condition.getPage(user);
		if(pageBean.getCurrent() > 1){
			Date now = new Date();
			// 判断是否是会员
			if(sysUser == null || sysUser.getVipEndTime() == null){
				throw new ServiceException("同城只对会员开放，请充值",788);
			}else{
				if(now.compareTo(sysUser.getVipEndTime()) > 0){
					throw new ServiceException("同城只对会员开放，请充值",788);
				}
			}
		}
		IPage<SysUser> page = baseMapper.selectPageUserListByCity(pageBean, user);
		for(SysUser su : page.getRecords()){
			su.setWechat(null);
			su.setInviteCode(null);
			su.setDistance(String.valueOf(Arith.div(su.getMi(), 1000.00, 2)));
			su.setCoinLevel(StringUtils.getCoinLevel(su.getPayNum()));
		}
		return Condition.getTableDataInfo(page.getRecords(), page.getTotal());
	}

	@Override
	public TableDataInfo getPageListByTopic(SysUser user) {
		user.setUserType(UserType.APP.getCode());
		if(user.getUserId() != null){
			SysUser sysUser = baseMapper.selectById(user.getUserId());
			if(sysUser != null){
				if(StringUtils.isBlank(user.getSex())){
					if("1".equals(sysUser.getSex())){
						user.setSex("0");
					}else{
						user.setSex("1");
					}
				}
				user.setLon(sysUser.getLon());
				user.setLat(sysUser.getLat());
			}
		}else{
			if(StringUtils.isBlank(user.getSex())){
				user.setSex("1");
			}
		}
		
		user.setAppId(null);
		
		IPage<SysUser> pageBean = Condition.getPage(user);
		
		IPage<SysUser> page = baseMapper.selectPageListByHot(pageBean, user);
		
		for(SysUser su : page.getRecords()){
			if("0".equals(su.getWechatStatus()) && StringUtils.isNotBlank(su.getWechat())){
				su.setWechatFlag(true);
			}else{
				su.setWechatFlag(false);
			}
			
			if(StringUtils.isNotBlank(su.getInviteCode()) && "1".equals(su.getWechatCheck())){
				su.setInvite(true);
				su.setWechatFlag(true);
			}else{
				su.setInvite(false);
			}
			su.setWechat(null);
			su.setInviteCode(null);
			su.setCoinLevel(StringUtils.getCoinLevel(su.getPayNum()));
		}
		
		return Condition.getTableDataInfo(page.getRecords(), page.getTotal());
	}

	@Override
	public TableDataInfo getPageListByIdCard(SysUser user) {
		user.setUserType(UserType.APP.getCode());
		if(user.getUserId() != null){
			SysUser sysUser = baseMapper.selectById(user.getUserId());
			user.setLon(sysUser.getLon());
			user.setLat(sysUser.getLat());
			if("0".equals(sysUser.getSex())){
				user.setSex("1");
			}else{
				user.setSex("0");
			}
		}
		
		user.setAppId(null);
		
		IPage<SysUser> page = baseMapper.selectPageListByIdCard(Condition.getPage(user), user);
		
		for(SysUser su : page.getRecords()){
			if("0".equals(su.getWechatStatus()) && StringUtils.isNotBlank(su.getWechat())){
				su.setWechatFlag(true);
			}else{
				su.setWechatFlag(false);
			}
			
			if(StringUtils.isNotBlank(su.getInviteCode()) && "1".equals(su.getWechatCheck())){
				su.setInvite(true);
				su.setWechatFlag(true);
			}else{
				su.setInvite(false);
			}
			su.setWechat(null);
			su.setInviteCode(null);
			su.setDistance(String.valueOf(Arith.div(su.getMi(), 1000.00, 2)));
			su.setCoinLevel(StringUtils.getCoinLevel(su.getPayNum()));
		}
		return Condition.getTableDataInfo(page.getRecords(), page.getTotal());
	}

	@Override
	public void addPlayStatus(SysUser user) {
		SysUser u = baseMapper.selectById(SecurityUtils.getUserId());
		if(!"1".equals(u.getIsManager())){
			throw new ServiceException("只有管理员可以操作");
		}
		SysUser sysUser = baseMapper.selectById(user.getUserId());
		if("2".equals(sysUser.getIsTip())){
			sysUser.setPlayStatus("1");
		}else if("3".equals(sysUser.getIsTip())){
			sysUser.setPlayStatus("2");
		}
		sysUser.setIsTip("0");
		baseMapper.updateById(sysUser);
	}

	@Override
	public TableDataInfo getPageListByPlay(SysUser user) {
		user.setUserType(UserType.APP.getCode());
		if(user.getUserId() != null){
			SysUser sysUser = baseMapper.selectById(user.getUserId());
			user.setLon(sysUser.getLon());
			user.setLat(sysUser.getLat());
		}
		
		user.setAppId(null);
		
		IPage<SysUser> page = baseMapper.selectPageListByPlay(Condition.getPage(user), user);
		
		for(SysUser su : page.getRecords()){
			if("0".equals(su.getWechatStatus()) && StringUtils.isNotBlank(su.getWechat())){
				su.setWechatFlag(true);
			}else{
				su.setWechatFlag(false);
			}
			
			if(StringUtils.isNotBlank(su.getInviteCode()) && "1".equals(su.getWechatCheck())){
				su.setInvite(true);
				su.setWechatFlag(true);
			}else{
				su.setInvite(false);
			}
			su.setWechat(null);
			su.setInviteCode(null);
			su.setDistance(String.valueOf(Arith.div(su.getMi(), 1000.00, 2)));
			su.setCoinLevel(StringUtils.getCoinLevel(su.getPayNum()));
		}
		return Condition.getTableDataInfo(page.getRecords(), page.getTotal());
	}

	@Override
	public void addIsTip(SysUser user) {
		SysUser sysUser = baseMapper.selectById(SecurityUtils.getUserId());
		if(StringUtils.isBlank(sysUser.getWechat())){
    		throw new ServiceException("请到个人主页完善微信号");
    	}
		if(!"0".equals(sysUser.getPlayStatus())){
			throw new ServiceException("不能重复申请");
		}
		sysUser.setIsTip(user.getIsTip());
		baseMapper.updateById(sysUser);
	}

	@Override
	public TableDataInfo getPageListByApply(SysUser user) {
		IPage<SysUser> page = baseMapper.getPageListByApply(Condition.getPage(user), user);
		return Condition.getTableDataInfo(page.getRecords(), page.getTotal());
	}

	@Override
	public List<SysUser> getRandomUserBySex(String sex) {
		if("0".equals(sex)){
			sex = "1";
		}else{
			sex = "0";
		}
		return baseMapper.getRandomUserBySex(sex);
	}

	@Override
	public TableDataInfo getUserListByOpen(SysUser user) {
		if("wx05c9893288d3dd64".equals(user.getAppId())){
			return null;
		}
		user.setIsShow("3");
		
		IPage<SysUser> pageBean = Condition.getPage(user);
		if(pageBean.getCurrent() > 2){
			// 需要登陆
			if(user.getUserId() == null){
				throw new ServiceException("请登陆", 401);
			}
		}
		
		if(user.getUserId() != null && user.getUserId() > 0){
			SysUser sysUser = baseMapper.selectById(user.getUserId());
			if(sysUser.getPayNum() > 200){
				user.setIsShow("2");
			}
			String sex = user.getSex();
			if(StringUtils.isNotBlank(sysUser.getSex())){
				if("0".equals(sysUser.getSex())){
					user.setSex("1");
				}else{
					user.setSex("0");
				}
			}else{
				user.setSex("1");
			}
			if(StringUtils.isNotBlank(sex)){
				if("-1".equals(sex)){
					user.setSex(null);
				}else{
					user.setSex(sex);
				}
			}
			user.setLon(sysUser.getLon());
			user.setLat(sysUser.getLat());
		}else{
			Address address = AddressUtils.getAddressByIP();
			user.setLon(address.getLng());
			user.setLat(address.getLat());
			if(StringUtils.isBlank(user.getSex())){
				user.setSex("1");
			}
			if("-1".equals(user.getSex())){
				user.setSex(null);
			}
		}
		
		user.setAppId(null);
		
		if(!"0".equals(user.getSearchType())){
			user.setIsShow("2");
		}
		
		String dataKey = "userList:"+pageBean.getCurrent()+":"+user.getSex()+":"+user.getSearchType()+":"+user.getIsShow();
		String totalKey = "total:"+pageBean.getCurrent()+":"+user.getSex()+":"+user.getSearchType()+":"+user.getIsShow();
		System.out.println(dataKey);
		System.out.println(totalKey);
		List<SysUser> dataList = redisCache.getCacheList(dataKey);
		Long total = redisCache.getCacheObject(totalKey);
		
		if(CollectionUtils.isEmpty(dataList) || "1".equals(user.getSearchType())){
			// 默认数据
			IPage<SysUser> page = baseMapper.selectPageUserListByOpen(pageBean, user);
			List<SysUser> userList = page.getRecords();
			// 其它数据
			user.setIsShow("1");
			IPage<SysUser> otherPage = baseMapper.selectPageUserListByOpen(pageBean, user);
			List<SysUser> otherList = otherPage.getRecords();
			
			// 数据重组
			for(int i=0;i<userList.size();i++){
				otherList.set(i, userList.get(i));
			}
			
			
			for(SysUser su : otherPage.getRecords()){
				if(StringUtils.isNotBlank(su.getAlbums())){
					int l = su.getAlbums().split(",").length;
					su.setAlbums(String.valueOf(l));
				}else{
					su.setAlbums("0");
				}
				su.setWechat(null);
				su.setInviteCode(null);
				su.setDistance(String.valueOf(Arith.div(su.getMi(), 1000.00, 2)));
				su.setCoinLevel(StringUtils.getCoinLevel(su.getPayNum()));
			}
			
			redisCache.setCacheList(dataKey, otherList);
			redisCache.setCacheObject(totalKey, otherPage.getTotal());
			redisCache.expire(dataKey, 60);
			redisCache.expire(totalKey, 60);
			dataList = otherList;
			total = otherPage.getTotal();
		}
		
		return Condition.getTableDataInfo(dataList, total);
	}

	@Override
	public SysUser getInfoByUserId(SysUser user) {
		SysUser sysUser = userMapper.selectById(user.getUserId());
		if(StringUtils.isNotBlank(sysUser.getWechat()) && "0".equals(sysUser.getWechatStatus())){
			sysUser.setWechatFlag(true);
		}else{
			sysUser.setWechatFlag(false);
		}
		sysUser.setWechat(null);
		sysUser.setInviteCode(null);
		sysUser.setCoinLevel(StringUtils.getCoinLevel(sysUser.getPayNum()));
		return sysUser;
	}

	@Override
	public TableDataInfo getUserListByOther(SysUser user) {
		user.setIsShow("3");
		
		IPage<SysUser> pageBean = Condition.getPage(user);
		if(pageBean.getCurrent() > 1){
			// 需要登陆
			if(user.getUserId() == null){
				throw new ServiceException("请登陆", 401);
			}
		}
		
		if(user.getUserId() != null && user.getUserId() > 0){
			SysUser sysUser = baseMapper.selectById(user.getUserId());
			user.setLon(sysUser.getLon());
			user.setLat(sysUser.getLat());
		}else{
			Address address = AddressUtils.getAddressByIP();
			user.setLon(address.getLng());
			user.setLat(address.getLat());
		}
		
		user.setAppId(null);
		
		IPage<SysUser> page = baseMapper.selectPageUserListByOther(pageBean, user);
		
		for(SysUser su : page.getRecords()){
			if(StringUtils.isNotBlank(su.getAlbums())){
				int l = su.getAlbums().split(",").length;
				su.setAlbums(String.valueOf(l));
			}else{
				su.setAlbums("0");
			}
			su.setWechat(null);
			su.setInviteCode(null);
			su.setDistance(String.valueOf(Arith.div(su.getMi(), 1000.00, 2)));
			su.setCoinLevel(StringUtils.getCoinLevel(su.getPayNum()));
		}
		return Condition.getTableDataInfo(page.getRecords(), page.getTotal());
	}

	@Override
	public List<SysUser> getRandomUserListBySex(SysUser user) {
		return baseMapper.getRandomUserListBySex(user);
	}

	@Override
	public Integer getShareUserCount(Long userId) {
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		SysUser entity = new SysUser();
		entity.setVisitUserId(userId);
		queryWrapper.setEntity(entity);
		return baseMapper.selectCount(queryWrapper);
	}

	@Override
	public TableDataInfo getUserListOtherByOpen(SysUser user) {
		user.setIsShow("2");
		
		IPage<SysUser> pageBean = Condition.getPage(user);
		if(pageBean.getCurrent() > 1){
			// 需要登陆
			if(user.getUserId() == null){
				throw new ServiceException("请登陆", 401);
			}else{
				if("1".equals(user.getSearchType())){
					SysUser loginUser = baseMapper.selectById(user.getUserId());
					if(loginUser.getVipEndTime() == null || loginUser.getVipEndTime().compareTo(new Date()) < 0){
						throw new ServiceException("同城只对会员开放，请开通会员", 788);
					}
				}
			}
		}
		
		if(user.getUserId() != null && user.getUserId() > 0){
			SysUser sysUser = baseMapper.selectById(user.getUserId());
			if(sysUser.getPayNum() > 200){
				user.setIsShow("2");
			}
			String sex = user.getSex();
			if(StringUtils.isNotBlank(sysUser.getSex())){
				if("0".equals(sysUser.getSex())){
					user.setSex("1");
				}else{
					user.setSex("0");
				}
			}else{
				user.setSex("1");
			}
			if(StringUtils.isNotBlank(sex)){
				if("-1".equals(sex)){
					user.setSex(null);
				}else{
					user.setSex(sex);
				}
			}
			user.setLon(sysUser.getLon());
			user.setLat(sysUser.getLat());
		}else{
			Address address = AddressUtils.getAddressByIP();
			user.setLon(address.getLng());
			user.setLat(address.getLat());
			if(StringUtils.isBlank(user.getSex())){
				user.setSex("1");
			}
			if("-1".equals(user.getSex())){
				user.setSex(null);
			}
		}
		
		user.setAppId(null);
		
		if(!"0".equals(user.getSearchType())){
			user.setIsShow("2");
		}
		
		/*// 默认数据
		// 其它数据
		IPage<SysUser> otherPage = baseMapper.selectPageUserListByOpen(pageBean, user);
		List<SysUser> otherList = otherPage.getRecords();*/
		
		
		
		// 默认数据
		IPage<SysUser> page = baseMapper.selectPageUserListByOpen(pageBean, user);
		List<SysUser> userList = page.getRecords();
		// 其它数据
		user.setIsShow("1");
		IPage<SysUser> otherPage = baseMapper.selectPageUserListByOpen(pageBean, user);
		List<SysUser> otherList = otherPage.getRecords();
		
		// 数据重组
		for(int i=0;i<userList.size();i++){
			otherList.set(i, userList.get(i));
		}
		
		for(SysUser su : otherPage.getRecords()){
			if(StringUtils.isNotBlank(su.getAlbums())){
				int l = su.getAlbums().split(",").length;
				su.setAlbums(String.valueOf(l));
			}else{
				su.setAlbums("0");
			}
			if(StringUtils.isNotBlank(su.getWechat()) && "0".equals(su.getWechatStatus())){
				su.setWechatFlag(true);
			}else{
				su.setWechatFlag(false);
			}
			su.setWechat(null);
			su.setInviteCode(null);
			su.setDistance(String.valueOf(Arith.div(su.getMi(), 1000.00, 2)));
			su.setCoinLevel(StringUtils.getCoinLevel(su.getPayNum()));
		}
		
		return Condition.getTableDataInfo(otherList, otherPage.getTotal());
	}

	@Override
	public List<SysUser> getUnPayList() {
		return baseMapper.getUnPayList();
	}

	@Override
	public TableDataInfo getPageListAuthByTopic(SysUser user) {
		if(user.getUserId() != null){
			SysUser sysUser = baseMapper.selectById(user.getUserId());
			if(sysUser != null){
				if(StringUtils.isBlank(user.getSex())){
					if("1".equals(sysUser.getSex())){
						user.setSex("0");
					}else{
						user.setSex("1");
					}
				}
			}
		}else{
			if(StringUtils.isBlank(user.getSex())){
				user.setSex("1");
			}
		}
		
		IPage<SysUser> page = baseMapper.selectPageListAuthByHot(Condition.getPage(user), user);
		
		for(SysUser su : page.getRecords()){
			if("0".equals(su.getWechatStatus()) && StringUtils.isNotBlank(su.getWechat())){
				su.setWechatFlag(true);
			}else{
				su.setWechatFlag(false);
			}
			
			if(StringUtils.isNotBlank(su.getInviteCode()) && "1".equals(su.getWechatCheck())){
				su.setInvite(true);
				su.setWechatFlag(true);
			}else{
				su.setInvite(false);
			}
			su.setWechat(null);
			su.setInviteCode(null);
			su.setCoinLevel(StringUtils.getCoinLevel(su.getPayNum()));
		}
		
		return Condition.getTableDataInfo(page.getRecords(), page.getTotal());
	}

	@Override
	public SysUser getRandomAskUser(Long userId) {
		SysUser user = new SysUser();
		user.setSex("0");
		if(userId != null){
			user = baseMapper.selectById(userId);
		}
		
		SysUser sysUser = new SysUser();
		sysUser.setSex("1");
		if(user != null){
			if("1".equals(user.getSex())){
				sysUser.setSex("0");
			}
		}
		List<SysUser> list = baseMapper.getRandomAskUser(sysUser);
		int rd = RandomUtil.randomInt(list.size());
		return list.get(rd);
	}

	@Override
	public void updateWxOpenIsNull(SysUser user) {
		baseMapper.updateWxOpenIsNull(user);
	}

	@Override
	public List<SysUser> getVipUserList(String appId) {
		return baseMapper.getVipUserList(appId);
	}

	@Override
	public IPage<SysUser> selectPageListByHot(IPage<SysUser> pageBean, SysUser user) {
		return baseMapper.selectPageListByHot(pageBean, user);
	}

	@Override
	public List<SysUser> getManagerList() {
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		SysUser entity = new SysUser();
		entity.setIsManager("1");
		queryWrapper.setEntity(entity);
		return baseMapper.selectList(queryWrapper);
	}
	
}
